﻿using ExamSelfTouch.Message;
using ExamSelfTouch.Tools;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using Xc.Core.Tools;
using System.Windows;
using ExamSelfTouch.Model;

namespace ExamSelfTouch.ViewModel
{
    public class LoginViewModel : ViewModelBase
    {
        private Login _loginwin;
        public RelayCommand SubmitCommand { get; private set; }

        private string _clientName;
                public string ClientName
        {
            get { return _clientName; }
            set
            {
                _clientName = value;
                RaisePropertyChanged("ClientName");
            }
        }


        public LoginViewModel(Login loginwin)
        {
            _loginwin = loginwin;
            SubmitCommand = new RelayCommand(SubmitCommandExec);
            ClientName = GetClientName();

            Messenger.Default.Register<SendSingleWindow>(this, (single) =>
            {
                var isShow = single.UseType == EnumUseWindowType.Show;
                switch (single.SingleWindow)
                {
                    case EnumSingleWindow.LoadingWindow:
                        FormTools.LoadingWindow(isShow);
                        break;
                    case EnumSingleWindow.QuestionImageWindow:
                        FormTools.QuestionImageWindow(isShow);
                        break;
                    case EnumSingleWindow.QuestionTextWindow:
                        FormTools.QuestionTextWindow(isShow);
                        break;
                    case EnumSingleWindow.QuestionVideoWindow:
                        FormTools.QuestionVideoWindow(isShow);
                        break;
                    case EnumSingleWindow.MainWindow://added by gzx
                        FormTools.MainWindow(isShow);
                        break;
                }
            });

            if (!String.IsNullOrEmpty(ClientName))
                Login();


            Messenger.Default.Register<LoginViewModel>(this, (o) =>
            {
                if (!string.IsNullOrEmpty(o.ClientName))
                {
                    Login();
                }
            });

            //AutoUploadScore();
           // testc();
            //test2();
        }

        private void testc()
        {
            
            //DbEntry.DropAndCreate(typeof(WebScore));
        }
        private void SubmitCommandExec()
        {
            Messenger.Default.Send<LoginViewModel>(this);
        }

        string GetClientName()
        {
            string value = "";
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var settings = config.AppSettings.Settings;
                var item = settings["ClientName"];
                if (item == null)
                {
                    config.AppSettings.Settings.Add("ClientName", "");
                }
                else
                {
                    value = item.Value;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message,ex);
                
            }
            
            return value;
        }

        string GetPassword()
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
                return (from ManagementObject mo in searcher.Get() select mo["SerialNumber"].ToString().Trim()).FirstOrDefault();
            }
            catch
            {
                return System.Environment.MachineName;
            }
        }

        private async Task Login()
        {
            //string cpuid = GetCpuID();
            string cpuid = GetPassword();
            string url = string.Format("Login?name={0}&password={1}", ClientName, cpuid);
             
            try
            {
                var result = await HttpBase2.PostAsJsonAsync<ResultData>(url, null);
                //ResultData result = await HttpBase2.GetAsync<ResultData>(url);
                if (result == null)
                {
                    MessageBox.Show("服务器异常，请联系管理员", "提示", MessageBoxButton.OK);
                    return;
                }
                if (result.status == 0 && !string.IsNullOrEmpty(result.session))
                {
                    HttpBase2.SESSION = result.session;
                    SaveClientName();
                    LogTool.WriteInfoLog("登录session:" + HttpBase2.SESSION);
                    Messenger.Default.Send<SendSingleWindow>(new SendSingleWindow(EnumUseWindowType.Show, EnumSingleWindow.MainWindow));

                    //AutoUploadScore();

                    _loginwin.Hide();
                }
                else if (result.status == 1)
                {
                    MessageBox.Show("用户名或密码错误，请联系管理员", "提示", MessageBoxButton.OK);
                }
            }
            catch (Exception ex)
            {
                string message = string.Empty;
                GetMessage(ex, ref message);
                MessageBox.Show(message, "提示", MessageBoxButton.OK);
            }
            

        }

        String GetCpuID()
        {
            try
            {
                ManagementClass mc = new ManagementClass("Win32_Processor");
                ManagementObjectCollection moc = mc.GetInstances();

                String strCpuID = null;
                foreach (ManagementObject mo in moc)
                {
                    strCpuID = mo.Properties["ProcessorId"].Value.ToString();
                    break;
                }
                return strCpuID;
            }
            catch
            {
                return "";
            }

        }

        //private async void AutoUploadScore()
        //{
        //    var scores = (from t in WebScore.Table where t.IsUploaded == false select t).ToList();
        //    var titleids = (from p in scores group p by p.titleId);
        //    foreach (var item in titleids)
        //    {
        //        var group = from d in scores where d.titleId == item.Key select d;
        //        ScoreData sd = new ScoreData() { nr = item.Key, session = HttpBase2.SESSION };
        //        List<score> score_list = new List<score>();
        //        foreach (var i in group)
        //        {
        //            score s = new score() { name = i.name, value = i.value };
        //            score_list.Add(s);
        //        }
        //        sd.items = score_list;


        //        try
        //        {
        //            var rdata = await HttpBase2.PostAsJsonAsync<ResultData>("Score", sd);
        //            if (rdata.status != -3)
        //            {
        //                foreach (var i in group)
        //                {
        //                    i.IsUploaded = true;
        //                    i.Save();
        //                }
        //            }
        //        }
        //        catch (Exception ex)
        //        {
        //            LogHelper.WriteLog(ex.Message, ex);
        //            Console.WriteLine(ex);
        //        }
        //    }
        //}



        private void SaveClientName()
        {
            Global.ClientName = ClientName;
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings["ClientName"].Value = this.ClientName;
            config.Save();
        }

        private void GetMessage(Exception ex, ref string msg)
        {
            LogHelper.WriteLog(ex.Message, ex);
            if (ex.InnerException != null)
            {
                GetMessage(ex.InnerException, ref msg);
            }
            else
            {
                msg = ex.Message;
            }
        }
        
    }
}
